import React, { useEffect, useRef, useState } from 'react'
import style from './compoments/style.module.css'
import { Button, Form, Input } from 'antd'
function Useradd() {


  const ref = useRef()
  const user_id = 'ok'
  const [arr, setArr] = useState([])
  let lt = () => {
    ref.current = new WebSocket(`ws://81.70.224.2:8003/koa/ws?user_id=${user_id}&server_id=300`)
    ref.current.onopen = () => {
      ref.current.send(JSON.stringify({ "type": "getChatList" }))
    }


    ref.current.onmessage = (e) => {
      console.log(e);
      const data = JSON.stringify(e.data)
      if (data.type === 'getChatList') {
        setArr(data.data)
      } else if (data.data === 'addMessage ') {
        ref.current.send(JSON.stringify({ "type": "getChatList" }))
      }
    }
  }


  useEffect(() => {
    lt()
  }, [])
  console.log(arr);

  const onfinish = (values) => {
    if (!values.text) {
      alert('不能为空')
      return
    }
    ref.current.send(JSON.stringify({ type: "addMessage", data: { message: values.text, type: 'text' } }))
  }

  return (
    <div className={style.box}>
      <div className={style.heart}>
        {
          arr.map((item) => {
            return (
              <div className={user_id === item.user_id ? style.list1 : style.list2}>
                <img src={user_id === item.user_id ? item.user_avatar : item.other_avatar} alt="" />
              </div>
            )
          })
        }
      </div>


      <Form onFinish={onfinish}>
        <Form.Item name='text'>
          <Input></Input>
        </Form.Item>
        <Form.Item>
          <Button htmlType='submit'>发送</Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Useradd
